package com.zhangwei.touch.vpi.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * @author zhangwei
 * @version V1.0
 * @Title: Advanced
 * @Package com.zhangwei.touch
 * @Description:-
 * @date 15/10/21 下午4:03
 *
 * 防止项目多个界面出现空白界面
 */

public class VpiPageAdapter extends PagerAdapter {
    private List<Fragment> fragmentList;
    private FragmentManager fm;
    private String[] titles;


    public VpiPageAdapter(List<Fragment> fragmentList, FragmentManager fm, String[] titles) {
        this.fragmentList = fragmentList;
        this.fm = fm;
        this.titles = titles;
    }

    public VpiPageAdapter(List<Fragment> fragmentList, FragmentManager fm) {
        this(fragmentList, fm, null);
    }


    @Override
    public int getCount() {
        return fragmentList != null ? fragmentList.size() : 0;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = fragmentList.get(position);
        if (!fragment.isAdded()) {
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(fragment, fragment.getClass().getName());
            ft.commitAllowingStateLoss();
            fm.executePendingTransactions();
        }
        View view = fragment.getView();
        if (view != null && view.getParent() == null) {
            container.addView(view);
        }

        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(fragmentList.get(position).getView());
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles == null ? super.getPageTitle(position) : titles[position];
    }
}
